﻿Imports System.ComponentModel
Imports System.Configuration.Install

Public Class InstallerForService

    Private Const cServiceDisplayName As String = "My Generic Service"
    Private Const cStartAfterInstall As String = "STARTAFTERINSTALL"
    Private Const cNETProcessName As String = "Net"
    Private Const cNETStart As String = "Start ""{0}"""
    Private Const cNETWaitTimeout As Integer = 5000
    Private Const cNETWaitError As String = "WARNING: Process took longer than expected to start, it may need to be restarted manually"

    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()

        'Add initialization code after the call to InitializeComponent
        Me.ServiceInstaller1.DisplayName = cServiceDisplayName
        Me.ServiceInstaller1.ServiceName = GetType(Service1).ToString
        Me.ServiceInstaller1.StartType = ServiceProcess.ServiceStartMode.Automatic
        Me.ServiceProcessInstaller1.Account = _
                                       ServiceProcess.ServiceAccount.NetworkService
    End Sub


    Private Sub InstallerForService_AfterInstall(ByVal sender As Object, _
                                                 ByVal e As InstallEventArgs) _
                                                            Handles Me.AfterInstall
        'Retrieve the user input (unchecked box can return empty string,
        'whereas a checked box will return "1")
        Dim startString As String = Me.Context.Parameters(cStartAfterInstall)
        If startString = "" Then Return
        Dim shouldStart As Boolean = CBool(startString)
        If Not shouldStart Then Return

        'Service should be started, so create a process and wait for completion
        Dim proc As Process = Process.Start(CreateNetStartProcessInfo)
        If Not proc.WaitForExit(cNETWaitTimeout) Then MsgBox(cNETWaitError)

    End Sub

    Private Function CreateNetStartProcessInfo() As ProcessStartInfo
        Dim x As New ProcessStartInfo(cNETProcessName, _
                                     String.Format(cNETStart, cServiceDisplayName))
        x.WindowStyle = ProcessWindowStyle.Hidden
        Return x
    End Function
End Class
